function Axios(config) {
    this.default = config;
}
// 发送请求 难点与重点
Axios.prototype.request = function (config) {
    return dispatchRequest(config);
}

function dispatchRequest(config) {
    return xhrAdapter(config)
}

function xhrAdapter(config) {
    console.log(config)
    return new Promise((resolve, reject) => {
        // 发送ajax请求
        let xhr = new XMLHttpRequest();
        // 初始化
        xhr.open(config.method, config.url);
        // 发送
        xhr.send();
        // 绑定事件
        xhr.onreadystatechange = function () {
            console.log(222)
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve({
                        config: config, // 配置对象
                        data: xhr.response, // 响应体
                        headers: xhr.getAllResponseHeaders(), // 响应头 字符串
                        request: xhr, // 请求对象
                        status: xhr.status, // 状态码
                        statusText: xhr.statusText // 相应状态字符串
                    })
                } else {
                    reject(new Error('请求失败，失败状态码为' + xhr.status))
                }
            }
        }
        if(config.cancelToken) {
            config.cancelToken.promise.then((resolve) => {
                xhr.abort();
                reject(new Error('请求已取消'))
            })
        }
    })
}

function CancelToken(executor) {
    var resolvePromise;
    this.promise = new Promise((resolve) => {
        resolvePromise = resolve;
    })

    executor(function() {
        console.log(111)
        resolvePromise();
    })
}

let context = new Axios({});
let axios = Axios.prototype.request.bind(context);
console.dir(axios)
let cancel = null;
let sendBtn = document.getElementById('send');
let cancelBtn = document.getElementById('cancel');
sendBtn.onclick = function () {
    if (cancel !== null) {
        cancel();
    }

    let cancelToken = new CancelToken(function(c) {
        cancel = c;
    })

    axios({ method: 'get', url: 'http://localhost:3000/posts', cancelToken:cancelToken }).then(res => {
        console.log(res);
    }).catch(err => {
        console.log(err)
    })
}
cancelBtn.onclick = function() {
    console.log(111)
    cancel();
}